/**
 * 数据字典管理
 */
$package("systemDict");
systemDict = {
    /**
     * 初始化方法
     */
    initSystemDictPage: function () {
        this.obj = {
            sysDicTableObj: $('#sysDicTable'),
            sysDicListObj: null,
            searchSysDicBtn: $('#searchSysDicBtn'),
            resetSysDicBtn: $('#resetSysDicBtn'),
            addSysDicBtn: $('#addSysDicBtn'),
            dicNameVal:$('#dicNameVal'),
            dicCodeVal:$('#dicCodeVal')
        };
        this.domVar = {
            unitDic: [],
            //[{property:"字段名",option:"操作类型",value:"值",propertytype:"数据类型"}]
            conditionJsonArray: '[{property:"dicLevel",option:"EQ",value:"1",propertytype:""}]'
        };
        this.initDict();//加载数据字典
        this.btnSysDictEvent();//按钮事件
        this.initSysDictDom();
    },

    initDict: function () {
        var self = this;
        /**************加载数据字典**************/
        //*********获取通用删除状态字典**********
        $.ajax({
            url: wwwroot + 'base/dictionary/getByCode/unitFlag',
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (result) {
                if (result.respCode == "200") {
                    self.domVar.unitDic = result.dataObj.toDict('dicCode',true);
                }
            }
        });
    },

    //初始化dom方法
    initSysDictDom: function () {
        var self = this;
        self.obj.sysDicListObj = self.obj.sysDicTableObj.dataTable({
            serverSide: true,//从后台请求数据
            processing: true, //显示加载
            bPaginate: true, //翻页功能
            bLengthChange: false, //改变每页显示数据数量
            bFilter: false, //过滤功能
            searching: false,//前端检索功能关闭
            bSort:false,//开关，是否让各列具有按列排序功能
            iDisplayLength: 10,
            //"bInfo": true,//页脚信息
            //"bStateSave": true,//状态保存，使用了翻页或者改变了每页显示数据数量，会保存在cookie中，
            // 下回访问时会显示上一次关闭页面时的内容。
            //"bAutoWidth": true,//自动宽度
            deferRender: true,//当处理大数据时，延迟渲染数据，有效提高Datatables处理能力
            sPaginationType: "full_numbers", //显示数字的翻页样式
            sScrollX: "100%",
            sScrollXInner: "110%",
            bScrollCollapse: true,
            oLanguage: {
                sLengthMenu: "每页显示 _MENU_ 条记录",
                sZeroRecords: "抱歉,没有找到数据",
                sInfo: "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                sInfoEmpty: "没有数据",
                sSearch: "搜索",
                sInfoFiltered: "(从 _MAX_ 条数据中检索)",
                oPaginate: {
                    sFirst: "首页",
                    sPrevious: "前一页",
                    sNext: "后一页",
                    sLast: "尾页"
                }
            },
            ajax: function (param, callback, setting) {
                param.conditionJsonArray = self.domVar.conditionJsonArray;
                $.ajax({
                    type: 'GET',
                    data: param,
                    dataType: 'json',
                    cache: false,
                    url: wwwroot + 'base/dictionary',
                    success: function (result) {
                        console.log(result);
                        callback(result);
                    }
                });
            },
            //装填数据
            columns: [
                {title: "字典名称", data: "dicName"},
                {title: "字典编码", data: "dicCode"},
                {title: "字典描述", data: "description",width:250},
                {
                    title: "状态", data: "dicFlag",width:80, render: function (value, type, full) {
                        return self.domVar.unitDic.getText(value, 'dicName');
                    }
                },
                {
                    title: "创建时间", data: "createTime",width:150,render: function (value, type, full) {
                        return new Date(value).format();
                    }
                },
                {
                    title: "修改时间", data: "modifyTime",width:150,render: function (value, type, full) {
                        return new Date(value).format();
                    }
                }
            ],
            //添加操作菜单
            columnDefs: [{
                title: '操作',
                data: null,
                width:200,
                targets: 6,//操作行列数
                render: function (value, type, row) {
                    var id = '"' + row.id + '"';
                    var html = "<a href='javascript:void(0);' onclick='systemDict.viewDic(" + id + ")'>" +
                        "<i class='fa fa-times'></i>查看详细</a>";
                    html += "<a href='javascript:void(0);' onclick='systemDict.editDic(" + id + ")'>" +
                        "<i class='fa fa-times'></i>修改</a>";
                    if (row.dicFlag == '1') {
                        html += "<a href='javascript:void(0);' onclick='systemDict.disableDic(" + id + ")'>" +
                            "<i class='fa fa-times'></i>禁用</a>";
                    } else if (row.dicFlag == '2') {
                        html += "<a href='javascript:void(0);' onclick='systemDict.enableDic(" + id + ")'>" +
                            "<i class='fa fa-times'></i>启用</a>";
                    }
                    html += "<a href='javascript:void(0);' onclick='systemDict.deleteDic(" + id + ")'>" +
                        "<i class='fa fa-times'></i>删除</a>";
                    return html;
                }
            }]

        });
    },
    btnSysDictEvent: function () {
        var self = this;
        //查询
        self.obj.searchSysDicBtn.unbind().bind('click',function () {
            var dicName = self.obj.dicNameVal.val();
            var dicCode = self.obj.dicCodeVal.val();
            var conditionJsonArray = [{property:"dicLevel",option:"EQ",value:"1",propertytype:""}];
            if(dicName && dicName!=''){
                conditionJsonArray.push({
                    property:"dicName",
                    option:"LIKEIGNORE",
                    value:dicName,
                    propertytype:""
                });
            }
            if(dicCode && dicCode!=''){
                conditionJsonArray.push({
                    property:"dicCode",
                    option:"LIKEIGNORE",
                    value:dicCode,
                    propertytype:""
                });
            }
            self.domVar.conditionJsonArray=JSON.stringify(conditionJsonArray);
            self.obj.sysDicListObj.fnReloadAjax();
        });
        //重置
        self.obj.resetSysDicBtn.unbind().bind('click',function () {
            self.obj.dicNameVal.val('');
            self.obj.dicCodeVal.val('');
            self.domVar.conditionJsonArray='[{property:"dicLevel",option:"EQ",value:"1",propertytype:""}]';
            self.obj.sysDicListObj.fnReloadAjax();
        });
        //添加
        self.obj.addSysDicBtn.unbind().bind('click',function () {
            sckWindow({
                size: 'lg',
                url: 'tpl/base/systemFunc/systemDictAdd.html',
                sureBtn: true,
                onSureClick: function () {
                    var data = $('#sysDicAddForm').getForm();
                    var sunDicList = [];
                    $('#subDicAddTable tbody').find('tr').each(function(){
                        //noinspection JSValidateTypes
                        var tdArr = $(this).children();
                            var dicName = tdArr.eq(0).find('input').val();
                            var dicCode = tdArr.eq(1).find('input').val();
                            var description = tdArr.eq(2).find('input').val();
                        sunDicList.push({dicName:dicName,dicCode:dicCode,description:description});
                    });
                    data.subDicList = sunDicList;
                    console.log(data);
                    $.ajax({
                        type:'POST',
                        dataType: 'json',
                        cache: false,
                        data:JSON.stringify(data),
                        headers: {'Content-type': 'application/json;character=UTF-8'},
                        url:wwwroot+'base/dictionary',
                        success:function (result) {
                            if(result.respCode=='201'){
                                closeSkyWindow();
                                self.obj.sysDicListObj.fnReloadAjax();
                                skyAlert("添加字典成功！");
                            }
                        },
                        error:function () {
                            closeSkyWindow();
                            skyAlert("添加字典失败！");
                        }
                    });

                },
                afterWinOpen: function () {
                    $('#addSubDictList').unbind().bind('click',function (){
                        $('#subDicAddTable tbody').append('<tr>' +
                            '<td><input class="form-control"></td>' +
                            '<td><input class="form-control"></td>' +
                            '<td><input class="form-control"></td>' +
                            '<td><i onclick="delSubDic(this)" class="icon icon-remove"></i></td>' +
                            '</tr>');
                    });
                    delSubDic=function (app){
                        app.closest('tr').remove();
                    }
                }
            });
        });
    },
    viewDic: function (id) {
        var self = this;
        sckWindow({
            size: 'lg',
            url: 'tpl/base/systemFunc/systemDictView.html',
            sureBtn: false,
            onSureClick: function () {
            },
            afterWinOpen: function () {
                $.ajax({
                    type:'GET',
                    dataType: 'json',
                    cache: true,
                    url:wwwroot+'base/dictionary/'+id,
                    success:function (result) {
                        if(result.respCode=='200'){
                            result.dataObj.dicFlag=self.domVar.unitDic.getText(result.dataObj.dicFlag, 'dicName');
                            $.each(result.dataObj.subDicList,function (i, item) {
                                $('#sysDicViewTable tbody').append('<tr>' +
                                    '<td>'+item.dicName+'</td>' +
                                    '<td>'+item.dicCode+'</td>' +
                                    '<td>'+item.description+'</td>' +
                                    '</tr>');
                            });
                            $('#sysDicViewForm').setForm(result.dataObj);
                        }
                    }
                });
            }
        });
    },
    editDic: function (id) {
        var self = this;
    },
    disableDic: function (id) {
        var self = this;
    },
    enableDic: function (id) {
        var self = this;
    },
    deleteDic: function (id) {
        var self = this;
        skyConform("确定要删除吗？",function () {
            $.ajax({
                type: 'DELETE',
                url: wwwroot + 'base/dictionary/'+id,
                headers: {'Content-type': 'application/json;character=UTF-8'},
                success: function (result) {
                    console.log(result);
                    var respMsg = "删除失败！";
                    if(result.respCode == '204'){
                        respMsg = "删除成功！";
                    }
                    self.obj.sysDicListObj.fnReloadAjax();
                    skyAlert(respMsg);
                }
            });
        })
    }
};
$(function () {
    systemDict.initSystemDictPage();
});